define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxEconomicLossEstimate";

    var fxEconomyLossMiddleFormHtml = sysPath + "/views/fxEconomicLossEstimateForm.html";
    var getFxEconomicLossEstimateController = function () {
        return getServer() + "/fxEconomyLossMiddles";
    };
    var getFxBuildingsController = function () {
        return getServer() + "/fxBuildingss";
    };
    var getFxVulnerabilityProvinceController = function () {
        return getServer() + "/fx/fxVulnerabilityProvinces";
    };
    var getFxDamagePercentController = function () {
        return getServer() + "/fxDamagePercents";
    };
    var getFxEconomicLossController = function () {
        return getServer() + "/fxEconomicLosss";
    };

    /**
     * 页面初始化
     */
    var buildingDamagePercent, buildingResetUnitPrice;
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("北京市", "北京市", "海淀区");

    };
    // 搜索栏省市区
    var initProvinceSelect = function (Province, City, Area) {
        //debugger;
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        //debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    createFxEconomicLossEstimateGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    //debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            if ($("#provinceSelect").val() == null) {
                Util.alert("请选择省");
                return;
            }
            if ($("#citySelect").val() == null) {
                Util.alert("请选择市");
                return;
            }
            if ($("#areaSelect").val() == null) {
                Util.alert("请选择区（县）");
                return;
            }
            //createFxEconomicLossEstimateGrid();
            mainMethod();

        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("北京市", "北京市", "海淀区");
        });
        $("#btnExport").click(function () {
            exportFxEconomicLossEstimateData();
        });
    }
    /**
     * 导出
     */
    var exportFxEconomicLossEstimateData = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        window.location.href = getFxEconomicLossEstimateController() + "/exportEstimate?province=" + province + "&city=" + city + "&area=" + area;
    };
    var mainMethod = function () {
        if (!buildingDamagePercent || !buildingResetUnitPrice) {
            queryFxDamagePercents();
            queryFxResetUnitPrice();
            var t = setInterval(function () {
                if (buildingDamagePercent && buildingResetUnitPrice) {
                    clearInterval(t);
                    var sType, temp_obj = {};
                    for (let i = 0; i < buildingDamagePercent.length; i++) {
                        sType = buildingDamagePercent[i].structureType;
                        temp_obj[sType] = {
                            "0": parseFloat(buildingDamagePercent[i].intact),
                            "1": parseFloat(buildingDamagePercent[i].slight),
                            "2": parseFloat(buildingDamagePercent[i].medium),
                            "3": parseFloat(buildingDamagePercent[i].serious),
                            "4": parseFloat(buildingDamagePercent[i].whole)
                        };
                    }
                    buildingDamagePercent = temp_obj;
                    console.log("damagePercent: ", buildingDamagePercent);
                    temp_obj = {};
                    for (let i = 0; i < buildingResetUnitPrice.length; i++) {
                        sType = buildingResetUnitPrice[i].structureType;
                        temp_obj[sType] = parseFloat(buildingResetUnitPrice[i].price);
                    }
                    buildingResetUnitPrice = temp_obj;
                    console.log("resetUnitPrice: ", buildingResetUnitPrice);
                    estimateFxEconomicLossByArea();
                } else {
                }
            }, 100);
        } else if (buildingDamagePercent && buildingResetUnitPrice) {
            console.log("-------damagePercent: ", buildingDamagePercent);
            console.log("-------resetUnitPrice: ", buildingResetUnitPrice);
            estimateFxEconomicLossByArea();
        }
    };
    var queryFxDamagePercents = function () {
        $.ajax({
            url: getFxDamagePercentController() + "/getFxDamagePercents",
            type: "get",
            success: function (result) {
                buildingDamagePercent = result;
            }
        });
    };
    var queryFxResetUnitPrice = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxEconomicLossController() + "/listFxEconomicLosss?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (result) {
                buildingResetUnitPrice = result;
            }
        });
    };

    var estimateFxEconomicLossByArea = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxBuildingsController() + "/getFxBuildingss?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (data) {
                console.log(data);
                if (data && data.length > 0) {
                    var dataStore = {"province": province, "city": city, "area": area};
                    var buildingIsFinished = {};
                    for (let i = 0; i < data.length; i++) {
                        buildingIsFinished[data[i].id] = false;
                        $.ajax({
                            url: getFxVulnerabilityProvinceController() + "/findFxVulnerabilityProvinces?province=" + data[i].province + "&city=" + data[i].city + "&area=" + data[i].area + "&structureType=" + data[i].structureType,
                            type: "get",
                            success: function (result) {
                                //console.log("result: ", result);
                                buildingIsFinished[data[i].id] = true;
                                if (result) {
                                    //console.log("structureType: ", data[i].structureType);
                                    var damageDegree, bDamagePercent = 0, bResetUnitPrice = 0;
                                    for (let j = 0; j < result.length; j++) {
                                        damageDegree = result[j].damageDegree;
                                        bDamagePercent = buildingDamagePercent[data[i].structureType][damageDegree] * 0.01;
                                        bResetUnitPrice = buildingResetUnitPrice[data[i].structureType];
                                        putDataToStore(dataStore, result, data, j, i, bDamagePercent, bResetUnitPrice, damageDegree);
                                    }
                                }
                                if (taskIsFinish(buildingIsFinished)) {
                                    console.log("############");
                                    console.log("dataStore: ", dataStore);
                                    updateEconomicLossMiddle(dataStore);
                                }
                            }
                        });
                    }
                } else {
                    $('#fxEconomicLossEstimateGrid').datagrid('loadData', {total: 0, rows: []});
                    $('#fxEconomicLossEstimateGrid').datagrid('appendRow', {});
                    var body = $("#fxEconomicLossEstimateGrid").data().datagrid.dc.body2;
                    var trs = body.find('table tbody').find("tr");
                    while (trs.eq(0).find("td").length > 1) {
                        if (trs.eq(0).find("td").length == 1) break;
                        trs.eq(0).find("td").eq(1).remove();
                    }
                    trs.eq(0).find("td").eq(0).attr("colspan", 6).attr("width", body.width()).css("text-align", "center").html("查询无数据");
                }
            }
        });
    };
    var putDataToStore = function (dataStore, result, data, j, i, bDamagePercent, bResetUnitPrice, damageDegree) {
        //面积*易损性值*建筑损坏损失比*重置单价
        var vulnerability = result[j].vulnerabilityVI;
        var loss = data[i].buildingArea * vulnerability * bDamagePercent * bResetUnitPrice;
        !dataStore["6"] && (dataStore["6"] = {});
        !dataStore["6"][damageDegree] ? (dataStore["6"][damageDegree] = loss) : dataStore["6"][damageDegree] += loss;

        vulnerability = result[j].vulnerabilityVII;
        loss = data[i].buildingArea * vulnerability * bDamagePercent * bResetUnitPrice;
        !dataStore["7"] && (dataStore["7"] = {});
        !dataStore["7"][damageDegree] ? (dataStore["7"][damageDegree] = loss) : dataStore["7"][damageDegree] += loss;

        vulnerability = result[j].vulnerabilityVIII;
        loss = data[i].buildingArea * vulnerability * bDamagePercent * bResetUnitPrice;
        !dataStore["8"] && (dataStore["8"] = {});
        !dataStore["8"][damageDegree] ? (dataStore["8"][damageDegree] = loss) : dataStore["8"][damageDegree] += loss;

        vulnerability = result[j].vulnerabilityIX;
        loss = data[i].buildingArea * vulnerability * bDamagePercent * bResetUnitPrice;
        !dataStore["9"] && (dataStore["9"] = {});
        !dataStore["9"][damageDegree] ? (dataStore["9"][damageDegree] = loss) : dataStore["9"][damageDegree] += loss;

        vulnerability = result[j].vulnerabilityX;
        loss = data[i].buildingArea * vulnerability * bDamagePercent * bResetUnitPrice;
        !dataStore["10"] && (dataStore["10"] = {});
        !dataStore["10"][damageDegree] ? (dataStore["10"][damageDegree] = loss) : dataStore["10"][damageDegree] += loss;
    };
    var updateEconomicLossMiddle = function (dataStore) {
        var p = dataStore.province, c = dataStore.city, a = dataStore.area, buildingIsFinished = {};
        for (let _key in dataStore) {
            if (_key == "province" || _key == "city" || _key == "area") continue;
            for (let damageDegree in dataStore[_key]) {
                buildingIsFinished[_key + damageDegree] = false;
                $.ajax({
                    url: getFxEconomicLossEstimateController() + "/getFxEconomyLossMiddles?province=" + p + "&city=" + c + "&area=" + a + "&earthquakeIntensity=" + _key + "&damageDegree=" + damageDegree,
                    contentType: "application/json",
                    type: "GET",
                    success: function (_data) {
                        //console.log(tt++, _key, damageDegree);
                        //console.log(_data);
                        if (_data && _data.length == 1) {
                            var _result = _data[0];
                            _result.calculatedValue = parseFloat(dataStore[_key][damageDegree].toFixed(4));
                            //console.log(dataStore[_key][damageDegree], "-----" ,_result.calculatedValue);
                            $.ajax({
                                url: getFxEconomicLossEstimateController(),
                                contentType: "application/json",
                                data: JSON.stringify(_result),
                                type: "put",
                                success: function (__data) {
                                    console.log(__data.message);
                                    if (__data.message == "修改失败!") Util.alert(p + c + a + '-' + _key + '-' + damageDegree + ': ' + __data.message);
                                    //slidebar.close();
                                    buildingIsFinished[_key + damageDegree] = true;
                                    taskIsFinish(buildingIsFinished) && (createFxEconomicLossEstimateGrid(), Util.alert("计算完成"));
                                }
                            });
                        } else {
                            //console.log(p + c + a + '-' + _key + '-' + damageDegree + ': ' + _data);
                            addFxEconomyLossMiddles(p, c, a, _key, damageDegree, buildingIsFinished);

                        }
                    }
                });
            }
        }
    };
    var addFxEconomyLossMiddles = function (province, city, area, intensity, damageDegree, buildingIsFinished) {
        var data = {
            province: province,
            city: city,
            area: area,
            earthquakeIntensity: intensity,
            damageDegree: damageDegree,
            isValid: "1"

        };
        $.ajax({
            url: getFxEconomicLossEstimateController(),
            contentType: "application/json",
            data: JSON.stringify(data),
            type: "post",
            success: function (data) {
                buildingIsFinished[intensity + damageDegree] = true;
                taskIsFinish(buildingIsFinished) && (estimateFxEconomicLossByArea());
            }
        });
    };
    var taskIsFinish = function (obj) {
        for (var _key in obj) if (!obj[_key]) return false;
        return true;
    }

    var createFxEconomicLossEstimateGrid = function () {
        $("#fxEconomicLossEstimateGrid").datagrid({
            url: getFxEconomicLossEstimateController() + "/getFxEconomyLossMiddles",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {
                    field: 'province',
                    title: '省',
                    width: '16%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '16%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '16%',
                    align: 'center'
                },
                {
                    field: 'earthquakeIntensity',
                    title: '烈度',
                    width: '12%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "6") {
                            return 'VI';
                        } else if (value == "7") {
                            return 'VII';
                        } else if (value == "8") {
                            return 'VIII';
                        } else if (value == "9") {
                            return 'IX';
                        } else if (value == "10") {
                            return 'X';
                        }
                    }
                },
                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    width: '16%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
                },
                {
                    field: 'calculatedValue',
                    title: '计算值（万元）',
                    width: '21.5%',
                    align: 'center',
                    //editor:{type:'numberbox',options:{precision:2}},
                    formatter: function (val, rowData, rowIndex) {
                        if (val != null) {
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
                    }
                }
            ]],
            onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxEconomicLossEstimateGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxEconomicLossEstimateGrid", "province,city,area,earthquakeIntensity");
                }
            },
//          onDblClickCell: function (index, field, value) {
//				$("#fxEconomicLossEstimateGrid").datagrid('endEdit', index);
//				debugger;
//				mergeCells("fxEconomicLossEstimateGrid", "province,city,area,structureType");
//        	},
            onAfterEdit: function (index, row, changes) {
//             $("#fxEconomicLossEstimateGrid").datagrid('endEdit', index);
//			    $.ajax({
//			        url : '要改变后台数据的controller路径?fieId1='+row.属性1,
//			        data:{fieId2:row.fieId}, //额外的参数
//			        dataType: "text",//响应结果为文本
//			        success:function (data) {
//			            $.messager.alert('消息', data);
//			        }
//			    });
                //console.log(index, row, changes);
                $.ajax({
                    url: getFxEconomicLossEstimateController(),
                    contentType: "application/json",
                    data: JSON.stringify(row),
                    type: "put",
                    success: function (data) {
                        Util.alert(data.message);
                        createFxEconomicLossEstimateGrid();
                    }
                });

            },
            toolbar: [{
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportFxEconomicLossEstimateData();
                    //alert("功能暂未实现");
                }
            }],
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxEconomicLossEstimateGrid", "province,city,area,earthquakeIntensity");
            },
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
            },
//          pagination: true,
//          pageSize: 10
        });
    };
    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxEconomicLossEstimateGrid').datagrid('validateRow', editIndex)) {
            $('#fxEconomicLossEstimateGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };

    //合并单元格方法
    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * @param colList 要合并table的id, 此例子中是tTable
     * @param colList 要合并的列,多个列用逗号分隔(例如："tempParam,flowCode,queryParam");
     */
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
    return {
        init: init
    };
});
